package ca.cbc.giscommon.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.Properties;

/**
 * @author: arash
 * Date: 11-08-15
 * Time: 6:33 PM
 * CBC.ca All rights reserved.
 */
public enum GISConfig {
    instance;
    private Logger logger = LoggerFactory.getLogger(GISConfig.class);

    private final String CONFIG_FILENAME = "gis.properties";
    private Properties properties = null;

    // in case of -1 do not change the connection timeout/read timeout 
    private static int CONNECTION_READ_TIMEOUT = -1;
    private static int CONNECTION_TIMEOUT = -1;

    static {
        try {
            CONNECTION_READ_TIMEOUT = Integer.parseInt(GISConfig.instance.getProperty("digest.connection.read.timeout"));
        } catch (Exception e) {
            // ignore - allow connection to default.
        }
        try {
            CONNECTION_TIMEOUT = Integer.parseInt(GISConfig.instance.getProperty("digest.connection.timeout"));
        } catch (Exception e) {
            // ignore - allow connection to default.
        }
    }

    public void changeConnectionTimeouts(URLConnection conn) {
        if (CONNECTION_READ_TIMEOUT != -1) conn.setReadTimeout(CONNECTION_READ_TIMEOUT);
        if (CONNECTION_TIMEOUT != -1) conn.setConnectTimeout(CONNECTION_TIMEOUT);
    }

    public String getProperty(String key) {
        if (properties == null) {
            synchronized (GISConfig.class) {
                if (properties == null) {
                    InputStream is = null;
                    try {
                        // load properties
                        is = GISConfig.class.getClassLoader().getResourceAsStream(CONFIG_FILENAME);
                        if (is == null) {
                            throw new FileNotFoundException(CONFIG_FILENAME + " not found");
                        }
                        properties = new Properties();
                        properties.load(is);
                    } catch (IOException e) {
                        logger.error("Error reading properties ", e);
                    } finally {
                        try {
                            assert is != null;
                            is.close();
                        } catch (IOException e) {
                            logger.error("Could not close file handler for property file", e);
                        }
                    }
                }
            }
        }
        return properties.getProperty(key);
    }
}
